package com.kcwx.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.kcwx.common.annotation.Log;
import com.kcwx.common.enums.BusinessType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.kcwx.common.constant.Constants;
import com.kcwx.common.core.domain.AjaxResult;
import com.kcwx.common.core.domain.entity.SysMenu;
import com.kcwx.common.core.domain.entity.SysUser;
import com.kcwx.common.core.domain.model.LoginBody;
import com.kcwx.common.core.domain.model.LoginUser;
import com.kcwx.common.core.domain.model.UserLoginInfo;
import com.kcwx.common.utils.SecurityUtils;
import com.kcwx.framework.web.service.SysLoginService;
import com.kcwx.framework.web.service.SysPermissionService;
import com.kcwx.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 */
@Api(tags = "系统管理-登录")
@RestController
public class SysLoginController {
	@Autowired
	private SysLoginService loginService;

	@Autowired
	private ISysMenuService menuService;

	@Autowired
	private SysPermissionService permissionService;

	/**
	 * 登录方法
	 * 
	 * @param loginBody 登录信息
	 * @return 结果
	 */
	@ApiOperation("登录方法")
	//@Log(title = "登录", businessType = BusinessType.OTHER)
	@PostMapping("/login")
	public AjaxResult login(@RequestBody LoginBody loginBody) {
		// 生成令牌
		String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());
		Map<String, Object> dataInfo = new HashMap<>();
		dataInfo.put(Constants.TOKEN, token);
		return AjaxResult.success(dataInfo);
	}

	/**
	 * 获取用户信息
	 * 
	 * @return 用户信息
	 */
	@ApiOperation("获取用户信息")
	@Log(title = "获取登录的用户信息", businessType = BusinessType.OTHER)
	@GetMapping("getInfo")
	public AjaxResult getInfo() {
		LoginUser loginUser = SecurityUtils.getLoginUser();
		SysUser user = loginUser.getUser();
		// 角色集合
		Set<String> roles = permissionService.getRolePermission(user);
		// 权限集合
		Set<String> permissions = permissionService.getMenuPermission(user);
		loginUser.setPermissions(permissions);
		//返回数据
		UserLoginInfo userLoginInfo = new UserLoginInfo();
		userLoginInfo.setUser(user);
		userLoginInfo.setRoles(roles);
		userLoginInfo.setPermissions(permissions);
		return AjaxResult.success(userLoginInfo);
	}

	/**
	 * 获取路由信息
	 * 
	 * @return 路由信息
	 */
	@ApiOperation("获取路由信息")
	@Log(title = "获取路由信息", businessType = BusinessType.OTHER)
	@GetMapping("getRouters")
	public AjaxResult getRouters() {
		Long userId = SecurityUtils.getUserId();
		List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
		return AjaxResult.success(menuService.buildMenus(menus));
	}
}
